执行自定义的SQL语句


1. extra

  • 有点类似于子查询

  • select 查询 -> 在 QuerySet 下的每一个对象添加对应的查询结果

book_list = Book.objects.all().extra(
    select={
        'is_meets': 'price > 60',
        'date_archive': 'date_format(publish_date, "%%Y-%%m")'
    }
)

'''
    查询结果:
    {'is_meets': 1, 'date_archive': '2019-05', 'price': Decimal('100.00'), 'title': '西游记', 'memo': None, 'id': 1, 'publish_date': datetime.date(2019, 5, 24)}
    {'is_meets': 0, 'date_archive': '2019-05', 'price': Decimal('50.00'), 'title': '红楼梦', 'memo': '说明', 'id': 2, 'publish_date': datetime.date(2019, 5, 27)}
'''

    • select_params -> 在 select 查询中传递参数

book_list = Book.objects.all().extra(
    select={
        'is_meets': 'price > "%s"',
        'date_archive': 'date_format(publish_date, "%%Y-%%m")'
    },
    select_params=[60]
)

  • where 条件查询 -> 查询出符合条件的数据

book_list = Book.objects.all().extra(
    where=['price >= 60']
)

    • params -> 在 where 查询中传递参数

book_list = Book.objects.all().extra(
    where=['price >= "%s"'],
    params=[60, ]
)

2.connection

  • 和PyMySQL模块类似

from django.db import connection
cursor = connection.cursor()  # cursor = connections['default'].cursor()
cursor.execute('SELECT * from app01_student where id = %s', [1])
ret = cursor.fetchone()